package com.wholesale;

import java.math.BigDecimal;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.datas.DbHelperAdapter;
import com.wholesale.datas.ShopCar;
import com.wholesale.utils.CartListAdapter;
import com.wholesale.utils.Constants;

public class CartLayout extends LinearLayout implements OnClickListener {
	private ViewFlipper viewFlipper;
	private Context context;
	private View baseView;
	private ListView bodyList;
	private Button leftButton;
	private Button rightButton;
	private TextView headView;
	private RelativeLayout loadingLayout;

	/**
	 * 其实是EDIT,ai...
	 */
	private boolean isDelete = false;
	private CartListAdapter cartListAdapter;
	private TextView totalNumView;
	private TextView totalPriceView;
	private ArrayList<ShopCar> data;

	// 构造函数
	public CartLayout(Context context, final ViewFlipper viewFlipper) {
		super(context);
		this.viewFlipper = viewFlipper;
		this.context = context;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.cart, this);
		bodyList = (ListView) baseView.findViewById(R.id.bodyList);
		leftButton = (Button) baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Edit");
		leftButton.setOnClickListener(this);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setText("Check out");
		rightButton.setOnClickListener(this);
		headView = (TextView) baseView.findViewById(R.id.title);
		headView.setText("Cart");
		bodyList.setSelector(R.drawable.details_list_bg);
		totalNumView = (TextView) baseView.findViewById(R.id.totalcount_text);
		totalPriceView = (TextView) baseView.findViewById(R.id.totalprice_text);
		loadingLayout = (RelativeLayout) baseView
				.findViewById(R.id.loadingLayout);
		// item 单击事件
		bodyList.setOnItemClickListener(moreClieckListener);
		cartListAdapter = new CartListAdapter(context, bodyList);
		cartListAdapter.setTotalView(totalNumView, totalPriceView);
		bodyList.setAdapter(cartListAdapter);
		CartListAsync cartListAsync = new CartListAsync(context);
		cartListAsync.execute((Void) null);

	}

	public void updateShopCar() {
		CartListAsync cartListAsync = new CartListAsync(context);
		cartListAsync.execute((Void) null);
	}

	// ListView 点击事件
	OnItemClickListener moreClieckListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			GoodsDetailLayout goodsDetailLayout = new GoodsDetailLayout(
					context, viewFlipper, "Cart", cartListAdapter.getItem(arg2)
							.getGoodsId());
			viewFlipper.addView(goodsDetailLayout);
			viewFlipper.showNext();
		}
	};

	class CartListAsync extends AsyncTask<Void, Integer, ArrayList<ShopCar>> {
		ProgressDialog pdialog;

		public CartListAsync(Context context) {
			// pdialog = new ProgressDialog(context);
			// pdialog.setTitle("Loading...");
			// pdialog.setMessage("Please wait...");
			// pdialog.setCancelable(true);
			// pdialog.setButton("cancel", new DialogInterface.OnClickListener()
			// {
			// public void onClick(DialogInterface dialog, int i) {
			// dialog.cancel();
			// CartListAsync.this.cancel(true);
			// }
			// });
			// pdialog.show();
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected ArrayList<ShopCar> doInBackground(Void... params) {
			DbHelperAdapter dbHelperAdapter = new DbHelperAdapter(context);
			dbHelperAdapter.open();
			data = dbHelperAdapter.getAll();
			dbHelperAdapter.close();
			return data;
		}

		@Override
		protected void onPostExecute(ArrayList<ShopCar> result) {
			int totalNum = 0;
			double totalprice = 0;
			for (ShopCar shopCar : result) {
				totalNum = totalNum + shopCar.getCartInfo().getGoodsNumber();
				totalprice = totalprice + shopCar.getCartInfo().getGoodsPrice()
						* shopCar.getCartInfo().getGoodsNumber();
			}
			totalNumView.setText("" + totalNum);
			totalPriceView.setText("" + getTwoDecimal(totalprice));
			cartListAdapter.clear();
			cartListAdapter.addItems(result);
			cartListAdapter.notifyDataSetChanged();
			// pdialog.dismiss();
			loadingLayout.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	private void sendBroadcastForShopCar() {
		Intent myIntent = new Intent();// 创建Intent对象
		myIntent.setAction("com.wholesale.utils.UpdateUIService");
		myIntent.putExtra("cmd", Constants.CMD_DELETECAR_SERVICE);
		myIntent.putExtra("from", "com.wholesale.CartLayout");
		((Activity) getContext()).sendBroadcast(myIntent);
	}

	private double getTwoDecimal(double d) {
		BigDecimal bd = new BigDecimal(d);
		double result = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return result;
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.leftBtn:
			if (cartListAdapter.getCount() > 0) {
				// InputMethodManager imm =
				// (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				// imm.hideSoftInputFromWindow(leftButton.getWindowToken(), 0);
				if (isDelete) {
					int count = cartListAdapter.getCount();
					DbHelperAdapter dbHelperAdapter = new DbHelperAdapter(
							context);
					dbHelperAdapter.open();
					for (int i = 0; i < count; i++) {
						dbHelperAdapter.update(cartListAdapter.getItem(i));
					}
					dbHelperAdapter.close();
					sendBroadcastForShopCar();
					isDelete = false;
				} else {
					isDelete = true;
				}
				if (isDelete) {
					leftButton.setText("Update");
				} else {
					leftButton.setText("Edit");
				}
				cartListAdapter.setDelete(isDelete);
				cartListAdapter.notifyDataSetChanged();
				bodyList.postInvalidate();
			}
			break;
		case R.id.rightBtn:
			if (cartListAdapter.getCount() > 0) {
				if (Constants.userInfo == null) {
					UserLoginLayout userLoginLayout = new UserLoginLayout(
							context, viewFlipper);
					viewFlipper.addView(userLoginLayout);
					viewFlipper.showNext();
				} else {
					if (data != null && data.size() > 0) {
						CheckOutLayout checkOutLayout = new CheckOutLayout(
								context, viewFlipper, data);
						viewFlipper.addView(checkOutLayout);
						viewFlipper.showNext();
					}
				}
			}
			break;
		default:
			break;
		}

	}
}
